package com.xinlijiankang.web.user;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xinlijiankang.respVO.Result;
import com.xinlijiankang.web.service.OperateService;
import com.xinlijiankang.web.utils.MD5;



@Controller
public class UserController {
	@Resource(name="operateService")
	private OperateService operateService;
	
	public static boolean isStrEmpty(String str){
		if (str == null || str.trim().isEmpty())
			return true;
		else return false;
	}
	

	/**
	 * 登陆
	 * 请求方法:userLogin 
	 * 传入参数
	 *    @param username String
	 *    @param password String
	 * 返回参数
	 *    @return Result String,String,String
	 */
	@RequestMapping("userLogin")
	@ResponseBody
	public Result login(String username,String password,HttpSession session) {
		Result result=new Result();
		if (!isStrEmpty(username)&&!isStrEmpty(password)){
			User user=operateService.findByName(User.class, username,"username");
			//MD5加密
			MD5 md5=new MD5();
			String md5pwd=md5.getMd5(password);
			if (user.getPassword().equals(md5pwd)){
				result.setStatus("200");
				result.setMesg("登陆成功");
				result.setData(null);
				session.setAttribute("user", user);
				return result;
			}
			else {
				result.setStatus("401");            //身份验证错误
				result.setMesg("用户名或密码错误");
				result.setData(null);
				return result;
			}
		}
		else {
			result.setStatus("401");            //身份验证错误
			result.setMesg("用户名或密码错误为空");
			result.setData(null);
			return result;
		}
	}
	
	/**
	 * 注册
	 * 请求方法:userRegist
	 *     @param username String
	 *     @param password String
	 * 返回参数
	 *     @return Result String,String,String
	 */
	@RequestMapping("userRegist")
	@ResponseBody
	public Result regist(String username,String password) {
		Result result=new Result();
		if (!isStrEmpty(username)&&!isStrEmpty(password)){
			User user=operateService.findByName(User.class, username,"username");
			if (user==null){
				User u=new User();
				MD5 md5=new MD5();
				u.setUsername(username);
				u.setPassword(md5.getMd5(password));
				operateService.saveOperate(u);
				result.setStatus("200");
				result.setMesg("注册成功");
				result.setData(null);
				return result;
			}
			else {
				result.setStatus("401");            //身份验证错误
				result.setMesg("用户名已存在");
				result.setData(null);
				return result;
			}
		}
		else {
			result.setStatus("401");            //身份验证错误
			result.setMesg("用户名或密码错误为空");
			result.setData(null);
			return result;
		}
	}
}
